﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace RecipeTracker
{
    [Serializable()]
    public class Category
    {
        //[XmlIgnore()]
        //private List<Category> mCategories;

        //[XmlIgnore()]
        //public List<Category> Categories
        //{
        //    get
        //    {
        //        if (mCategories == null)
        //            mCategories = new List<Category>();
        //        return mCategories;
        //    }
        //    set { mCategories = value; }
        //}

        public static List<Category> Categories = new List<Category>();
        public static Dictionary<int, Category> CategoryLookup = new Dictionary<int, Category>();

        [XmlAttribute("id")]
        public int Id
        {
            get;
            set;
        }

        [XmlAttribute("name")]
        public string Name
        {
            get;
            set;
        }

        public Category()
        {
            Id = 0;
            Name = string.Empty;
        }

        public Category(int id, string name)
        {
            Id = id;
            Name = name;
        }

        public static void SaveCategories()
        {
            SaveCategories("RecipeCategories.xml");
        }

        public static void SaveCategories(string fileName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.Encoding = Encoding.UTF8;
            XmlWriter writer = XmlWriter.Create(fileName, settings);
            XmlSerializer x = new XmlSerializer(Categories.GetType());
            x.Serialize(writer, Categories);
            writer.Close();
        }

        public static void LoadCategories()
        {
            LoadCategories("RecipeCategories.xml");
        }

        public static void LoadCategories(string fileName)
        {
            XmlReader reader = XmlReader.Create(fileName);
            XmlSerializer x = new XmlSerializer(Categories.GetType());
            Categories = x.Deserialize(reader) as List<Category>;
            foreach (Category c in Categories)
            {
                CategoryLookup.Add(c.Id, c);
            }

            reader.Close();
        }

        public override string ToString()
        {
            return "Category: " + Name;
        }
    }
}
